﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Toom.CellularAutomata.Debug
{
	public class CAPerformanceTrackerItem
	{
		public CAPerformanceTrackerItem(string name)
		{
			this.name = name;

			this.measurementSum = 0.0;
			this.measurementCount = 0;
		}

		public string name;
		private double measurementSum;
		public double measurementCount;

		public void AddMeasurement( double measurement )
		{
			measurementSum += measurement;
			measurementCount++;
		}

		public double GetAverage()
		{
			if ( measurementCount == 0 )
				return double.NaN;

			return measurementSum / measurementCount;
		}

		public void Clear()
		{
			this.measurementCount=0;
			this.measurementSum=0.0;
		}

	}

	
	public class CAPerformanceTracker
	{
		public CAPerformanceTracker()
		{
			items = new Dictionary<string,CAPerformanceTrackerItem>();
		}

		private Dictionary<string,CAPerformanceTrackerItem> items;

		public void CreateNewTracker( string name)
		{
			CAPerformanceTrackerItem newItem = new CAPerformanceTrackerItem( name );
			items.Add( name,newItem );
		}


		public void UpdateTracker( string name, double newMeasurement )
		{
			if ( !items.ContainsKey( name ) )
				CreateNewTracker( name );

			items[name].AddMeasurement( newMeasurement );
		}


		public string GetAllStats()
		{
			StringBuilder sb = new StringBuilder();
			foreach( CAPerformanceTrackerItem i in items.Values )
			{
				sb.AppendFormat( "{0}: {1:0.000000} in {2} measurements", i.name, i.GetAverage(), i.measurementCount );
				sb.AppendLine();
			}
			return sb.ToString();
		}

		public void ClearAllStats()
		{
			foreach ( CAPerformanceTrackerItem t in items.Values )
				t.Clear();
		}

	}


}
